from openai import OpenAI

client = OpenAI()


def calculator(expression):
    return eval(expression)


# 运算表达式
def test(i, j):
    return i * j


tools = [
    {
        "type": "function",
        "function": {
            "name": "test",
            "description": "计算两个数值相加的结果",
            "parameters": {
                "type": "object",
                "properties": {
                    "i": {
                        "type": "number",
                        "description": "需要计算的数值 i"
                    },
                    "j": {
                        "type": "number",
                        "description": "需要计算的数值 j "
                    }
                }
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculator",
            "description": "运行加减乘除运算的表达式。",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "需要运行的算术表达式"
                    }
                }
            }
        }
    },
]

messages = [{"role": "user", "content": "700+800"}]

response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=messages,
    tools=tools
)

response_message = response.choices[0].message

messages.append(response_message)

import json

tool_calls = response_message.tool_calls

if tool_calls:
    available_functions = {
        "calculator": calculator,
    }
    for tool_call in tool_calls:
        function_name = tool_call.function.name
        if function_name == 'calculator':
            function_args = json.loads(tool_call.function.arguments)
            function_response = calculator(function_args.get('expression'))
            messages.append({
                "tool_call_id": tool_call.id,
                "role": "tool",
                "name": function_name,
                "content": str(function_response),
            })
        elif function_name == 'test':
            function_args = json.loads(tool_call.function.arguments)
            function_response = test(int(function_args.get('i')), int(function_args.get('j')))
            messages.append({
                "tool_call_id": tool_call.id,
                "role": "tool",
                "name": function_name,
                "content": str(function_response),
            })
        second_response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages
        )
        print(second_response.choices[0].message.content)
